package com.cac.demo.controller.msworkbinbasic;

import com.alibaba.fastjson.JSON;
import com.cac.demo.entity.msworkbinbasic.MsWorkbinBasicDTO;
import com.cac.demo.service.msworkbinbasic.MsWorkbinBasicService;
import com.cac.demo.util.adapter.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.cac.demo.util.adapter.BusinessUtil.getSortExpColumnName;


@RestController
@Api(tags = "缓存料箱维护接口")
@RequestMapping("/msworkbin/")
public class MsWorkbinBasicRest {
    @Autowired
    private MsWorkbinBasicService msWorkbinBasicService;

    /**
     * 按条件分页查询
     * @param map
     * @return
     */
    @PostMapping("/searchByPage")
    @ApiOperation(value = "按条件分页查询")
    public ResponseMsg<QueryRespBean<MsWorkbinBasicDTO>> searchByPage(@ApiParam(value = "查询条件" , name = "queryReqBean")@RequestBody Map map   ){
        ResponseMsg<QueryRespBean<MsWorkbinBasicDTO>> responseMsg = new ResponseMsg<>();
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        MsWorkbinBasicDTO searchParams = JSON.parseObject(searchParamsParams, MsWorkbinBasicDTO.class);

        QueryReqBean<MsWorkbinBasicDTO> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);

        if (StringUtils.hasText(queryReqBean.getSidx()) && StringUtils.hasText(queryReqBean.getSord())) {
            String sordExp = getSortExpColumnName(queryReqBean.getSidx(), queryReqBean.getSord(), MsWorkbinBasicDTO.class);
            if (StringUtils.hasText(sordExp)) {
                queryReqBean.setSortExp(sordExp);
            }
        }
        if (StringUtils.hasText(queryReqBean.getKeyWord())) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            MsWorkbinBasicDTO searchKeyWordParam = JsonHelper.getInstance().readValue(queryReqBean.getKeyWord(), dateFormat, new TypeReference<MsWorkbinBasicDTO>() {
            });
            queryReqBean.setSearchParams(searchKeyWordParam);
        }

        QueryRespBean<MsWorkbinBasicDTO> result = msWorkbinBasicService.searchMsWorkbinBasicByPage(queryReqBean, ContextCommonHolder.getOrgId(),queryReqBean.getSortExp());
        List<MsWorkbinBasicDTO> result1 = msWorkbinBasicService.searchMsWorkbinBasicByPage(searchParams, ContextCommonHolder.getOrgId(),queryReqBean.getSortExp());
        if(result1.size()==0){
            responseMsg.setRetCode("201").setMessage("未查询到数据").setResponseBody(result);
        }
        else responseMsg.setResponseBody(result);
        return  responseMsg;
    }

    @PostMapping("/searchMsWorkbin")
    @ApiOperation(value = "查询子表")
    public ResponseMsg<QueryRespBean<Map<String, String>>> searchMsWorkbin(@ApiParam(value = "查询条件" , name = "queryReqBean")@RequestBody Map map   ){
        ResponseMsg<QueryRespBean<Map<String, String>>> responseMsg = new ResponseMsg<>();
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        MsWorkbinBasicDTO searchParams = JSON.parseObject(searchParamsParams, MsWorkbinBasicDTO.class);

        QueryReqBean<MsWorkbinBasicDTO> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);

        if (StringUtils.hasText(queryReqBean.getSidx()) && StringUtils.hasText(queryReqBean.getSord())) {
            String sordExp = getSortExpColumnName(queryReqBean.getSidx(), queryReqBean.getSord(), MsWorkbinBasicDTO.class);
            if (StringUtils.hasText(sordExp)) {
                queryReqBean.setSortExp(sordExp);
            }
        }
        if (StringUtils.hasText(queryReqBean.getKeyWord())) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            MsWorkbinBasicDTO searchKeyWordParam = JsonHelper.getInstance().readValue(queryReqBean.getKeyWord(), dateFormat, new TypeReference<MsWorkbinBasicDTO>() {
            });
            queryReqBean.setSearchParams(searchKeyWordParam);
        }

        QueryRespBean<Map<String, String>> result = msWorkbinBasicService.searchMsWorkbin(queryReqBean, ContextCommonHolder.getOrgId(),queryReqBean.getSortExp());
        responseMsg.setResponseBody(result);
        return  responseMsg;

    }
    /**
     * 新增数据信息
     * @param
     * @return responseMsg返回数据库操作情况
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增一条数据信息")
    public ResponseMsg<Map> save(@ApiParam(value = "需要新增的数据" , name = "msMsWorkbinBasicDTO") @RequestBody HashMap<String, Object> map){
        ResponseMsg<Map> responseMsg =  new ResponseMsg<>();
        Map reMsg = new HashMap();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String createdBy = (String) request.getSession().getAttribute("account");
        if (Objects.isNull(createdBy)||"".equals(createdBy)) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("请重新登录！");
            return responseMsg;
        }
        int cnt = msWorkbinBasicService.queryWorkbinCode(map.get("workbinCode").toString());
        if (cnt>0)
        {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("已存在该缓存箱编码："+map.get("workbinCode").toString()+"！");
            return responseMsg;
        }
        int s = 0;
        int f = 0;
        try {
            s+=msWorkbinBasicService.insertMsWorkbinBasic(map);
            ;
        }catch(Exception e)
        {
            e.printStackTrace();
            f++;
        }
    reMsg.put("成功：", s);
        reMsg.put("失败：", f);
        if (s == 0 && f == 0) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("新增失败！");

        }
        if (s == 0 && f != 0) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("新增失败！");

        }
        if (s != 0 && f == 0) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("新增成功！");
        }
        return responseMsg;
    }
    /**
     * 修改数据信息
     * @param map
     * @return
     */

    @PostMapping("/update")
    @ApiOperation(value = "修改单个数据信息")
    public ResponseMsg<Map> update(@ApiParam(value = "修改的数据", name = "msMsWorkbinBasicDTO")@RequestBody HashMap<String, Object> map){
        ResponseMsg<Map> responseMsg = new ResponseMsg<>();
        Map reMsg = new HashMap();
        int s = 0;
        int f = 0;
        if(map.get("msWorkbinId")!= null){
            try {
                msWorkbinBasicService.updateMsWorkbinBasic(map);
                s++;
            }catch(Exception e)
            {
                e.printStackTrace();
                f++;
            }
        }
        else f++;
        reMsg.put("成功：", s);
        reMsg.put("失败：", f);
        if (s == 0 && f != 0) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("修改失败！");

        }
        if (s != 0 && f == 0) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("修改成功！");
        }
        return responseMsg;
    }

    /**
     * 按主键单条删除
     * @param map
     * @return ResponseMsg<Integer>
     */
    @PostMapping("/deleteById")
    @ApiOperation(value = "根据主键id删除数据")
    public ResponseMsg<Map> deleteById(@ApiParam(value = "被删除数据的主键ID" ,name = "id")@RequestBody HashMap<String, Object> map) {
        ResponseMsg<Map> responseMsg = new ResponseMsg<>();
        Map reMsg = new HashMap();
        int s = 0;
        int f = 0;
        List<HashMap<String, Object>> ids = (List<HashMap<String, Object>>) map.get("data");
        if(ids.size()==0){
            return responseMsg.setRetCode("201").setMessage("请选中需要删除的数据");
        }
        for(int i = 0 ;i<ids.size();i++){
            HashMap<String, Object> map1 = ids.get(i);
            String id = (String) map1.get("msWorkbinId");
            if(map1.get("msWorkbinId")!=null){
                msWorkbinBasicService.deleteMsWorkbinBasicById(id);
                s++;
            }
            else f++;
        }
        reMsg.put("成功：", s);
        reMsg.put("失败：", f);
        if (s == 0 && f != 0) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("删除失败！");

        }
        if (s != 0 && f == 0) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("删除成功！");
        }
        if (s != 0 && f != 0) {
            responseMsg.setRetCode("202");
            responseMsg.setMessage("删除有失败项！");
            responseMsg.setResponseBody(reMsg);
        }
        return responseMsg;
    }
    @PostMapping("queryWorkbinMaterial")
    public PageInfo queryWorkbinMaterial(@RequestBody HashMap map){
        HashMap queryMap = (HashMap) map.get("queryParam");
        HashMap page = (HashMap) map.get("page");
        int currentPage = Integer.parseInt(page.get("currentPage").toString());
        int pageSize = Integer.parseInt(page.get("pageSize").toString());
        return msWorkbinBasicService.queryWorkbinMaterial(queryMap,currentPage,pageSize);
    }
    @PostMapping("updateWorkbinMaterial")
    public ResponseMsg updateWorkbinMaterial(@RequestBody HashMap map){
        return msWorkbinBasicService.updateWorkbinMaterial(map);
    }

    @PostMapping("SetEmptyBoxes")
    public ResponseMsg updateSetEmptyBoxes(){
        return msWorkbinBasicService.updateSetEmptyBoxes();
    }
}
